package com.qf.common.pay.service.impl;

import com.github.binarywang.wxpay.bean.order.WxPayMwebOrderResult;
import com.github.binarywang.wxpay.bean.request.BaseWxPayRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.util.SignUtils;
import com.qf.common.pay.config.WxPayProperties;
import com.qf.common.pay.dto.PayDTO;
import com.qf.common.pay.param.FinishPayParam;
import com.qf.common.pay.param.PayParam;
import com.qf.common.pay.param.RefundParam;
import com.qf.common.pay.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * @Classname WxPayServiceImpl
 * @Description TODO
 * @Date 2025-06-05 14:39
 * @Created by 老任与码
 */
@Slf4j
@Service
public class WxPayServiceImpl implements PayService {

    @Resource
    private WxPayProperties wxPayProperties;

    @Resource
    private WxPayService wxPayService;

    @Override
    public String createPay(PayDTO payDTO) {
        //调用微信统一下单接口
        WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
        // orderRequest.setOpenid();
        // 设置支付方式
        orderRequest.setTradeType(WxPayConstants.TradeType.MWEB);
        orderRequest.setNotifyUrl(wxPayProperties.getNotifyUrl());
        orderRequest.setOutTradeNo(payDTO.getOrderNo());
        orderRequest.setTotalFee(BaseWxPayRequest.yuanToFen(payDTO.getAmount().toString()));
        orderRequest.setBody("微信支付订单");
        orderRequest.setSpbillCreateIp(InetAddress.getLoopbackAddress().getHostAddress());

        //计算签名 给前端使用
        Map<String, String> paySignInfo = new HashMap<>();
        String timeStamp = String.valueOf(System.currentTimeMillis() / 1000);
        String nonceStr = String.valueOf(System.currentTimeMillis());
        paySignInfo.put("appId", wxPayProperties.getAppId());
        paySignInfo.put("nonceStr", nonceStr);
        paySignInfo.put("timeStamp", timeStamp);
        paySignInfo.put("signType", "MD5");
        String paySign = SignUtils.createSign(paySignInfo, WxPayConstants.SignType.MD5, wxPayProperties.getMchKey(), new String[0]);
        orderRequest.setSign(paySign);

        WxPayMwebOrderResult result = null;
        try {
            result = wxPayService.createOrder(orderRequest);
            log.info("微信统一下单接口调用完成: {}", result);
        } catch (Exception e) {
            log.error("微信统一下单接口调用失败: {}", e.getMessage(), e);
            throw new RuntimeException("微信统一下单接口调用失败");
        }
        String encode = null;
        try {
            encode = URLEncoder.encode(wxPayProperties.getRedirectUrl(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        log.info(result.getMwebUrl() + "&redirect_url=" + encode);
        return result.getMwebUrl() + "&redirect_url=" + encode;
    }

    @Override
    public void notify(HttpServletRequest request, HttpServletResponse response, Consumer<FinishPayParam> consumer) {

    }

    @Override
    public void closePay(String outTradeNo) {

    }

    @Override
    public String payStatus(String outTradeNo) {
        return "";
    }

    @Override
    public void returnNotify(HttpServletRequest request, HttpServletResponse response,Consumer<FinishPayParam> consumer) {

    }

    @Override
    public String refundOrder(RefundParam refundParam) {
        return "";
    }
}
